package vip.xiaonuo.biz.modular.nccAi.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * ClassName:NccRequest
 * Description: ncc 的请求方法类
 * @Author:薛守立
 * @CreateTime:2025/4/17 10:41
 */
public class NccRequest<T> {

    private static Logger logger = LoggerFactory.getLogger(NccRequest.class);

    /**
     * get请求（Map入参）
     * @param url
     * @param params
     */
    public static String getMethod(String url, Map<String, String> params) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            URIBuilder builder = new URIBuilder(url);
            if(params != null){
                for (String key : params.keySet()){
                    builder.addParameter(key, params.get(key));
                }
            }
            URI uri = builder.build();
            // 执行请求
            HttpGet httpGet = new HttpGet(uri);
            response = httpClient.execute(httpGet);
            // 判断相应状态
            if(response.getStatusLine().getStatusCode() == 200) result = EntityUtils.toString(response.getEntity(),"UTF-8");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * post 请求（map入参, 指定请求方式）
     * @param url
     * @param params
     * @return
     */
    public static String postMethodByType(String url,  Map<String, String> params, String type) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";

        HttpPost httpPost = new HttpPost(url);
        try {
            // 构建请求参数
            StringEntity entity = new StringEntity(params.toString());
            entity.setContentEncoding("utf-8");
            entity.setContentType(type);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200) result = EntityUtils.toString(response.getEntity(),"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * post 请求（javaBean入参）
     * @param url
     * @param req
     * @return
     */
    public String postMethod(String url, T req) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";

        HttpPost httpPost = new HttpPost(url);
        try {
            // 构建请求参数
            String json = JSON.toJSONString(req);
            StringEntity entity = new StringEntity(json);
            entity.setContentEncoding("utf-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == 200) result = EntityUtils.toString(response.getEntity(),"UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                response.close();
                httpClient.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * post 请求（javaBean入参,restTemplate请求）
     * @param url
     * @param req
     * @return
     */
    public String postMethodTemplate(String url, T req) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAcceptCharset(Collections.singletonList(StandardCharsets.UTF_8));
        HttpEntity<T> entity = new HttpEntity<>(req, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            HttpStatus statusCode = (HttpStatus) response.getStatusCode();
            System.out.println("Status Code: " + statusCode);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 调用ncc影像上传接口
     * @param fileName
     * @param businessSerialNo
     * @param url
     * @return
     */
    public String uploadFile(File file, String fileName, String businessSerialNo, String url){
        HashMap<String, Object> paramMap = new HashMap<>();
        // 文件上传只需将参数中的键指定（默认file），值设为文件对象即可，对于使用者来说，文件上传与普通表单提交并无区别
        paramMap.put("fileByte", file);
        paramMap.put("fileParamName", fileName);
        paramMap.put("businessSerialNo", businessSerialNo);
        paramMap.put("fileName", fileName);
        paramMap.put("docName", fileName);
        String res= HttpUtil.post(url, paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(res);
        Integer status = jsonObject.getInt("status");
        String msg = "";
        if (null!=jsonObject.getStr("msg")) {
            msg = jsonObject.getStr("msg");
        } else if(null !=jsonObject.getStr("message")) {
            msg = jsonObject.getStr("message");
        }
        if (null != status && (status == 14 || status == 16 || status == 200)){
              logger.info("ncc文件上传请求接口，响应结果：{}", msg);
        } else {
            throw new RuntimeException("ncc影像上传接口请求错误");
        }
        return msg;
    }

    /**
     * 另外的请求方法
     * @param baseUrl
     * @param paramMap
     * @param mediaType
     * @param headers
     * @param json
     * @return
     * @throws Exception
     */
    public static String doPost(String baseUrl, Map<String, String> paramMap, String mediaType, Map<String, String> headers, String json) throws Exception {
        HttpURLConnection urlConnection = null;
        InputStream in = null;
        OutputStream out = null;
        BufferedReader bufferedReader = null;
        String result = null;

        try {
            StringBuffer sb = new StringBuffer();
            sb.append(baseUrl);
            String line;
            if (paramMap != null) {
                sb.append("?");
                Iterator var13 = paramMap.entrySet().iterator();

                while(var13.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry)var13.next();
                    String key = (String)entry.getKey();
                    line = (String)entry.getValue();
                    sb.append(key + "=" + line).append("&");
                }

                baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
            }

            URL urlObj = new URL(baseUrl);
            urlConnection = (HttpURLConnection)urlObj.openConnection();
            urlConnection.setConnectTimeout(50000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.addRequestProperty("content-type", mediaType);
            if (headers != null) {
                Iterator var35 = headers.keySet().iterator();

                while(var35.hasNext()) {
                    String key = (String)var35.next();
                    urlConnection.addRequestProperty(key, (String)headers.get(key));
                }
            }

            out = urlConnection.getOutputStream();
            out.write(json.getBytes("UTF-8"));
            out.flush();
            int resCode = urlConnection.getResponseCode();
            if (resCode != 200 && resCode != 201 && resCode != 202) {
                in = urlConnection.getErrorStream();
            } else {
                in = urlConnection.getInputStream();
            }

            bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            StringBuffer temp = new StringBuffer();

            for(line = bufferedReader.readLine(); line != null; line = bufferedReader.readLine()) {
                temp.append(line).append("\r\n");
            }

            String ecod = urlConnection.getContentEncoding();
            if (ecod == null) {
                ecod = Charset.forName("UTF-8").name();
            }

            result = new String(temp.toString().getBytes("UTF-8"), ecod);
            return result;
        } catch (Exception var30) {
            throw var30;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException var29) {
                    throw var29;
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (IOException var28) {
                    throw var28;
                }
            }

            if (in != null) {
                try {
                    in.close();
                } catch (IOException var27) {
                    throw var27;
                }
            }

            urlConnection.disconnect();
        }
    }

    public static String postFile(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            // 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            connection.setRequestProperty("Authorization", "Bearer OBd50jf3p3jynd5p1Zqtx3ndqIJWuiTF");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }
}
